import DataStore from 'lowdb'
import LodashId from 'lodash-id'
import FileSync from 'lowdb/adapters/FileSync'
import path from 'path'
import fs from 'fs-extra'
import { remote, app } from 'electron'

const APP = process.type === 'renderer' ? remote.app : app
const STORE_PATH = APP.getPath('userData')

if (process.type !== 'renderer') {
    if (!fs.pathExistsSync(STORE_PATH)) {
        fs.mkdirpSync(STORE_PATH)
    }
}

const adapter = new FileSync(path.join(STORE_PATH, '/data.json'))

const db = DataStore(adapter)
db._.mixin(LodashId)

if (!db.has('db_config').value()) {
    db.set('db_config', []).write()
}

if (!db.has('project_config').value()) {
    db.set('project_config', []).write()
}

if (!db.has('template_config').value()) {
    db.set('template_config', []).write()
}

export default db

export function copyFile(srcPath){
    fs.writeFileSync(
        path.join(STORE_PATH, '/data.json'),
        fs.readFileSync(srcPath)
    );
}